<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
      fixed
    />
    <!-- 上拉加载 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多数据了"
      @load="onLoad"
      :immediate-check="false"
    >
      <!-- 渲染文章art-item组件 -->
      <art-item
        v-for="item in searchList"
        :key="item.art_id.toString()"
        :article="item"
        :closeable="false"
      ></art-item>
    </van-list>
  </div>
</template>

<script>
import { getSearchResultApi } from '@/api/searchApi.js'
import ArtItem from '@/components/ArtItem/Artitem.vue'
export default {
  name: 'SearchResult',
  data () {
    return {
      page: 1,
      //   存搜索结果
      searchList: [],
      //   判断是否加载数据
      loading: false,
      //   判断数据是否加载完成
      finished: false,
      // 缓存关键词
      preKw: ''
    }
  },
  props: ['kw'],
  created () {
    this.initSearchList()
  },
  activated () {
    // 每次进入缓存，判断关键词是否等于上次缓存的关键词，如果不等于，重置信息并发请求
    if (this.preKw !== '' && this.kw !== this.preKw) {
      this.page = 1
      //   存搜索结果
      this.searchList = []
      //   判断是否加载数据
      this.loading = false
      //   判断数据是否加载完成
      this.finished = false
      // 重新发送请求
      this.initSearchList()
    }
  },
  deactivated () {
    // 每当离开组件缓存时，把kw值给到preKw
    this.preKw = this.kw
  },
  methods: {
    //   初始化搜索结果数据
    async initSearchList () {
      //  调用Api接口
      const { data: res } = await getSearchResultApi(this.kw, this.page)
      if (res.message === 'OK') {
        //  转存数据,旧数据在前，新数据在后
        this.searchList = [...this.searchList, ...res.data.results]
        //  重置loading为false
        this.loading = false
        // 判断数据是否加载完毕
        if (res.data.results.length === 0) {
          this.finished = true
        }
        // 页码值加1
        this.page += 1
      }
    },
    //   触发上拉加载
    onLoad () {
      this.initSearchList()
    }
  },
  components: {
    ArtItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
